package com.idp.app.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.idp.app.dto.*;
import com.idp.app.entity.SyAjxxEntity;
import com.idp.app.excel.SyAjxxExcelDto;
import com.idp.app.excel.SyAjxxImportListener;
import com.idp.app.mapper.SyAjxxMapper;
import com.idp.app.mapper.SySjzdMapper;
import com.idp.app.service.SyAjxxService;
import com.idp.app.util.DateUtils;
import com.idp.common.enums.MessageEnum;
import com.idp.common.error.SystemException;
import com.idp.common.model.PageModel;
import com.idp.system.mapper.SysDictionaryMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户表Service实现类
 *
 * @author Simon
 */
@Slf4j
@Service("syAjxxService")
public class SyAjxxServiceImpl implements SyAjxxService {

    @Autowired
    private SyAjxxMapper syAjxxMapper;
    @Autowired
    private SySjzdMapper sySjzdMapper;
    @Autowired
    private SysDictionaryMapper sysDictionaryMapper;

    @Override
    public PageModel<SyAjxxDto> findByPage(SyAjxxSearchParamDto syAjxxSearchDto) {
        PageModel<SyAjxxDto> page = new PageModel<>();
        List<SyAjxxDto> list = syAjxxMapper.getList(syAjxxSearchDto);
        list.stream().forEach(e -> {
            String ajlb = e.getAjlb();
            if (null != ajlb && !ajlb.equals("")) {
                SySjzdDto byId = sySjzdMapper.getById(ajlb);
                e.setIconUrl(byId.getTb());
            }
        });
        page.setList(list);
        return page;
    }

    @Override
    public SyAjxxDto getById(String id) {

        if (ObjectUtil.isEmpty(id)) {
            throw new SystemException(MessageEnum.PARAM_ERROR);
        }

        SyAjxxDto syAjxxDto = syAjxxMapper.getById(id);

        if (syAjxxDto == null) {
            throw new SystemException(MessageEnum.DATA_NOT_EXIST);
        }
        String ajsj = syAjxxDto.getAjsj();
        boolean flag = DateUtils.validateAndFormat(ajsj);
        if (!flag) {
            String s = DateUtils.reformatDate(ajsj);
            syAjxxDto.setAjsj(s);
        }
        return syAjxxDto;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(SyAjxxDto syAjxxDto) {

        SyAjxxEntity syAjxxEntity = BeanUtil.toBean(syAjxxDto, SyAjxxEntity.class);

        syAjxxMapper.insert(syAjxxEntity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SyAjxxDto syAjxxDto) {

        SyAjxxEntity syAjxxEntity = syAjxxMapper.selectById(syAjxxDto.getId());

        if (syAjxxEntity == null) {
            throw new SystemException(MessageEnum.DATA_NOT_EXIST);
        }
        CopyOptions copyOptions = new CopyOptions();
        copyOptions.setIgnoreNullValue(true);
        BeanUtil.copyProperties(syAjxxDto, syAjxxEntity, copyOptions);

        syAjxxMapper.updateById(syAjxxEntity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(String id) {

        SyAjxxEntity syAjxxEntity = syAjxxMapper.selectById(id);

        if (syAjxxEntity == null) {
            throw new SystemException(MessageEnum.DATA_NOT_EXIST);
        }

        syAjxxMapper.deleteById(id);
    }

    @Override
    public void importExcel(MultipartFile file) {
        InputStream in = null;

        try {
            in = file.getInputStream();

            SyAjxxImportListener importListener = new SyAjxxImportListener(syAjxxMapper);
            EasyExcel.read(in, SyAjxxExcelDto.class, importListener).sheet().doRead();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new SystemException("导入失败");
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public List<SyAjxxLxDto> getAllLxNum(ScreenCommonDto screenCommonDto) {
        return syAjxxMapper.getAllLxNum(screenCommonDto);
    }

    @Override
    public List<com.idp.system.dto.SyAjxxKjfbDto> getKjfb(ScreenCommonDto screenCommonDto) {
        List<com.idp.system.dto.SyAjxxKjfbDto> childList = sysDictionaryMapper.getChildList("00c34fd933bd46bc937c6142ad3e45ad");
        childList.stream().forEach(e -> {
            Integer ct = syAjxxMapper.getAjNum(e.getId());
            e.setNum(ct);
        });
        return childList;
    }

    @Override
    public SyAjxxSjfwDto getSjzlSjkd(ScreenCommonDto screenCommonDto) {
        SyAjxxSjfwDto dto = new SyAjxxSjfwDto();
        //数据总量
        Integer sjzl = syAjxxMapper.getSjzl(screenCommonDto);
        dto.setSjzl(sjzl);
        // 时间跨度
        Integer sjkd = syAjxxMapper.getSjkd(screenCommonDto);
        dto.setSjkd(sjkd);
        // 区域范围
        List<com.idp.system.dto.SyAjxxKjfbDto> childList = sysDictionaryMapper.getChildList("00c34fd933bd46bc937c6142ad3e45ad");
        dto.setQyfw(childList.size());
        // 数据类别
        List<String> list = syAjxxMapper.getSjlb(screenCommonDto);
        dto.setSjlb(list.size());
        return dto;
    }

    @Override
    public SyAjxxJczljczsDto getJczljczs(ScreenCommonDto screenCommonDto) {
        SyAjxxJczljczsDto dto = new SyAjxxJczljczsDto();

        //基层治理检查指数
        List<ZhjczslbParDto> list = syAjxxMapper.getJczljczsList(screenCommonDto.getDqbm());
        List<ZhjczslbDto> zhjczslbDtos = new ArrayList<>();
        list.stream().forEach(e -> {
            ZhjczslbDto zhjczslbDto = new ZhjczslbDto();
            String dictCode = e.getDictCode();
            LambdaQueryWrapper<SyAjxxEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SyAjxxEntity::getLx, dictCode);
            Integer allCt = syAjxxMapper.selectCount(queryWrapper);
            zhjczslbDto.setLx(e.getDictName());
            Integer cct = e.getCt() == null ? 0 : e.getCt();
            // 进行除法并设置精度为两位小数，使用四舍五入
            BigDecimal result = new BigDecimal("0");
            if( allCt != 0 ){
                 result = new BigDecimal((double) cct / allCt).multiply(new BigDecimal("100")).setScale(2, RoundingMode.HALF_UP);
            }
            zhjczslbDto.setZb(result);
            zhjczslbDtos.add(zhjczslbDto);
        });
        dto.setZhjczslb(zhjczslbDtos);

        //查询主题总数
        List<String> lxList = syAjxxMapper.getJczljczsCount(screenCommonDto.getDqbm());
        // 综合检查指数
        BigDecimal result = new BigDecimal("0");
        if (lxList.size() > 0) {
            // 使用Stream求和，相加后除以10并保留两位小数
            result = zhjczslbDtos.stream().map(ZhjczslbDto::getZb)  // 提取zb字段
                    .reduce(BigDecimal.ZERO, BigDecimal::add)  // 相加
                    .divide(BigDecimal.valueOf(lxList.size()), 2, RoundingMode.HALF_UP);  // 除以10并保留两位小数
        }
        dto.setZhjczs(result);
        return dto;
    }

    @Override
    public SyAjxxAjslDto getAjxxxx(ScreenCommonDto screenCommonDto) {
        return syAjxxMapper.getAjxxxx(screenCommonDto);
    }

    @Override
    public List<SyAjxxDateDto> getAjslByDate(ScreenCommonDto screenCommonDto) {
        return syAjxxMapper.getAjslByDate(screenCommonDto);
    }

    @Override
    public List<SyAjxxKjfbDto> getZtKjfb(ScreenCommonDto screenCommonDto) {
        return syAjxxMapper.getZtKjfb(screenCommonDto);
    }

    @Override
    public List<SyAjxxKjfbDto> getZtAjlb(ScreenCommonDto screenCommonDto) {
        return syAjxxMapper.getZtAjlb(screenCommonDto);
    }

    @Override
    public List<SyAjxxDto> getSjlbList(SyAjxxSearchDto syAjxxSearchDto) {
        return syAjxxMapper.getSjlbList(syAjxxSearchDto);
    }

    @Override
    public void exportExcel(SyAjxxSearchExportDto syAjxxDto, HttpServletResponse response) {
        /*List<SyAjxxDto> list = syAjxxMapper.getListInfore(syAjxxDto);
        List<SyAjxxExcelDto> excelList = BeanUtil.copyToList(list, SyAjxxExcelDto.class);

        // 设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = null;
        try (OutputStream out = response.getOutputStream()) {
            fileName = URLEncoder.encode("导出数据", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(out, SyAjxxExcelDto.class).autoCloseStream(Boolean.TRUE).sheet("Sheet1").doWrite(excelList);
        } catch (IOException e) {
            throw new RuntimeException("导出失败", e);
        }*/

        // 设置响应头
        /*response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");

        // 设置文件名并处理中文编码问题
        String fileName = null;
        try {
            fileName = URLEncoder.encode("导出数据", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            // 使用EasyExcel写出数据到response的输出流中
            EasyExcel.write(response.getOutputStream(), SyAjxxExcelDto.class).sheet("Sheet1").doWrite(excelList);
        } catch (UnsupportedEncodingException e) {
            throw new SystemException("导出失败!");
        } catch (IOException e) {
            throw new SystemException("导出失败啦!");
        }*/
    }

    /*@Override
    public void exportExcel(SyAjxxSearchExportDto syAjxxDto, HttpServletResponse response) {
        List<SyAjxxDto> list = syAjxxMapper.getListInfo(syAjxxDto);
        List<SyAjxxExcelDto> excelList = BeanUtil.copyToList(list, SyAjxxExcelDto.class);

        OutputStream out = null;

        try {
            out = response.getOutputStream();

            EasyExcel.write(out, SyAjxxExcelDto.class).sheet("案件信息").doWrite(excelList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new SystemException("导出失败");
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }*/

    @Override
    public List<SyAjxxDto> findAjByPage(SyAjxxSearchDto syAjxxSearchDto) {
        List<SyAjxxDto> list = syAjxxMapper.findAjByPage(syAjxxSearchDto);
        list.stream().forEach(e -> {
            String ajlb = e.getAjlb();
            if (null != ajlb && !ajlb.equals("")) {
                SySjzdDto byId = sySjzdMapper.getById(ajlb);
                e.setIconUrl(byId.getTb());
            }
        });
        return list;
    }

    @Override
    public List<ReportDto> getReport(ScreenParamDto screenParamDto) {
        return syAjxxMapper.getReport(screenParamDto);
    }

    @Override
    public List<SyAjxxExportDto> getListInfo(SyAjxxSearchExportDto syAjxxDto) {
        return syAjxxMapper.getListInfo(syAjxxDto);
    }

    @Override
    public List<SyAjxxExportDto> getListInfo1(SyAjxxSearchExportDto syAjxxDto) {
        return syAjxxMapper.getListInfo1(syAjxxDto);
    }

}
